!> \brief This program extract all the variables results listed in
!! "./input_files/varlist.txt" from all files listed in
!! "./input_files/filelist.txt" and saves the results in "./output_file.csv"

program main
   use mprint
   implicit none
   integer :: io !< input-output status
   integer :: nv !< number of variables
   integer :: nf !< number of files in the file list
   integer :: td !< Open input files ( 0 = no, 1 = yes)
   integer :: i1, i2 !< Dummy variables

   integer, parameter :: nfls = 100 !< Max. file list size
   integer, parameter :: nvls = 100 !< Max. var. list size
   integer, parameter :: nlen = 300 !< Max. string length

   character (len=nlen) :: str            !< Dummy string
   character (len=nlen) :: text_editor    !< text editor name
   character (len=nlen) :: filelist(nfls) !< list of files
   character (len=nlen) :: varlist(nvls)  !< list of variables

   character (len=10) :: vartype(nvls)    !< list of the type of the variables
   character (len=20) :: varlabel(nvls)   !< list of the label of variables

   logical :: lexist !< A logical variable

   !
   ! Reading ogen options file
   !
   open(10,file="./input_files/options.txt")

   read(10,*) td
   read(10,*) text_editor

   close(10)

   !
   ! Reading file list
   !
   if ( td == 1 ) call system( trim(adjustl(text_editor)) // &
      " ./input_files/filelist.txt")

   open(10,file="./input_files/filelist.txt")
   nf = 0 ! number of files
   do
      read(10,"(A)",iostat=io) str

      if ( io /= 0 ) exit

      if ( str /= "" ) then

         inquire(file = str, exist = lexist)

         if (.not. lexist) then

            write(*,"(A)") "Error: The following file does not exist:"

            write(*,"(A)") trim(adjustl(str))

            stop

         end if

         nf = nf + 1

         filelist(nf) = str

      end if

   end do

   close(10)

   !
   ! Reading var list
   !
   if ( td == 1 ) call system( trim(adjustl(text_editor)) // &
      " ./input_files/varlist.txt")

   open(10,file="./input_files/varlist.txt")
   nv = 0 ! number of variables
   do
      read(10,"(A)",iostat=io) str

      if ( io /= 0 ) exit

      if ( str /= "" ) then

         nv = nv + 1

         i1 = 1
         i2 = scan(str,'&')

         if ( i2 /= 0 ) then

            vartype(nv) = trim(adjustl(str(i1:i2-1)))

            str = str(i2+1:len(str))

            i2 = scan(str,'&')

            varlabel(nv) = trim(adjustl(str(i1:i2-1)))

            str = str(i2+1:len(str))

            varlist(nv) = trim(adjustl(str))

         end if

      end if

   end do

   close(10)

   ! Printing in the csv format

   call print_csv( nf, nv, nlen, filelist, varlist, vartype, varlabel)

   ! Printing in the tex format

   call print_tex( nf, nv, nlen, filelist, varlist, vartype, varlabel)

   ! Printing in the data format

   call print_dat( nf, nv, nlen, filelist, varlist, vartype, varlabel)

end program

